//
//  SLFingerCreateVC.m
//  SlockApp
//
//  Created by 凯朱 on 2024/7/29.
//

#import "SLFingerCreateVC.h"
#import "SLAccessDurtionVC.h"
#import "SLAccessOneTimeVC.h"
#import <Lottie/Lottie-Swift.h>
#import <SlockApp-Swift.h>
@interface SLFingerCreateVC (){
    CGFloat _curProgress;
    NSString *_accessId;
    BOOL _isUploading;
}
@property (nonatomic, strong)LottieAnimationView *animation;
@end

@implementation SLFingerCreateVC

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setUpSubViews];
    [ZCTool connectDeviceWith:kCurClickDevice toast:kLocalString(@"Connecting...") finish:^(BOOL isSuccess) {
        if (isSuccess) {
            [self startCreateFinger];
        }
    }];
}

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    //取消录入
    [[SLBluetoothManager sharedManager] addFingerAccessWith:_keyModel isManager:YES isCancel:YES finish:nil];
}

-(void)backBtnClicked{
    if (_isUploading) {
        return;
    }
    [super backBtnClicked];
    //取消录入
    [[SLBluetoothManager sharedManager] addFingerAccessWith:_keyModel isManager:YES isCancel:YES finish:nil];
}

-(void)startCreateFinger{
    _isUploading = NO;
    [[SLBluetoothManager sharedManager] addFingerAccessWith:self->_keyModel isManager:YES isCancel:NO finish:^(NSString *result, NSString *curStep, NSString *accessId, SLEnumCreateFingerStatus code) {
        
        if (code == SLEnumCreateFingerStatusTimeout) {
            [self showAlertWithTitle:kLocalString(@"Record timeout") message:kLocalString(@"Please note")];
        }else if (code == SLEnumCreateFingerStatusRepeat){
            [self showAlertWithTitle:kLocalString(@"Repeated Fingerprint") message:kLocalString(@"The fingerprint already exists. Please try again or delete the existing fingerprint first.")];
        }
        else if (code == SLEnumCreateFingerStatusOverMax){
            [SLTipAlertView showWith:kLocalString(@"Oops!\nThe fingerprint storage is full!") content1:kLocalString(@"Your smart padlock G1 can store up to 40 fingerprints. Please delete existing fingerprints if you need to add a new one.") content2:@"" doneBtn:kLocalString(@"OK") cancelBtn:@"" action:^(NSInteger index) {
                [self backToAccessManageVc:NO];
            }];
        }
        else if (code == SLEnumCreateFingerStatusNormal){
            if ([result isEqualToString:@"fc"]) {
                self->_curProgress = [curStep integerValue];
                [self updateProgress];
            }else if ([result isEqualToString:@"fd"]){//录入失败
                [self showAlertWithTitle:kLocalString(@"Entry failure") message:kLocalString(@"")];
            }else if ([result isEqualToString:@"ff"]){
                if (accessId.length == 0) {
                    [self showAlertWithTitle:kLocalString(@"Entry failure") message:kLocalString(@"")];
                    return;
                }
                self->_isUploading = YES;
                self->_accessId = accessId;
                [self uploadUserData];
                self->_curProgress = [curStep integerValue];
                [self updateProgress];
            }
        }
    }];
}

-(void)showAlertWithTitle:(NSString *)title message:(NSString *)message{
    [SLTipAlertView showWith:title content1:message content2:@"" doneBtn:kLocalString(@"Retry") cancelBtn:kLocalString(@"Cancel") action:^(NSInteger index) {
        if (index == 1) {
            [AnimationLoader resetAnimationWithAnimationView:self->_animation];
            [self startCreateFinger];
        }else{
            [self backToAccessManageVc:NO];
        }
    }];
}

-(void)setUpSubViews{
    self.title = kLocalString(@"Set fingerprint");
    _tipLbl.text = kLocalString(@"Touch the fingerprint pad to close the circle.");
    _tipLbl2.text = kLocalString(@"Lift and reposition your finger on the pad at different angles to get a more accurate fingerprint record.");
    _curProgress = 0;
    _sureBtn.btnStyle = 1;
    _sureBtn.hidden = YES;
    //添加动画
    _animation = [AnimationLoader loadAnimationFrom:@"FingerprintLoading" into:self.bgView];
    [_sureBtn setTitle:kLocalString(@"Next") forState:UIControlStateNormal];
}

- (IBAction)nextAction:(id)sender {
    [self backToAccessManageVc:YES];
}

-(void)backToAccessManageVc:(BOOL)isSuccess{
   
    UIViewController *accessVc = [UIViewController viewControllerWithClassName:@"SLAccessSettingVC"];
    UIViewController *managerVc = [UIViewController viewControllerWithClassName:@"SLAccessManagerVC"];
    
    //成员下添加指纹
    if (_isAddFinger) {
        if (accessVc) {
            [self.navigationController popToViewController:accessVc animated:YES];
        }else{
            [self.navigationController popViewControllerAnimated:YES];
        }
        [[NSNotificationCenter defaultCenter] postNotificationName:@"kRefreshAccessSettingVc" object:nil];
        
        return;
    }
    
    //添加成员
    if (accessVc) {
        [self.navigationController popToViewController:accessVc animated:YES];
    }else if(managerVc){
        [self.navigationController popToViewController:managerVc animated:YES];
    }else{
        [self.navigationController popToRootViewControllerAnimated:YES];
    }
    
    if (isSuccess) {
        [[NSNotificationCenter defaultCenter] postNotificationName:@"kAddAccessSuccess" object:@{@"model":_keyModel}];
        kNotifyRefreshDevcieList;
    }
}

-(void)updateProgress{
//    AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
     if (_curProgress == 6) {
         [AnimationLoader playAnimationWithAnimationView:_animation for:1];
     }else{
         CGFloat oneTime = 0.5;//总共3秒
         [AnimationLoader playAnimationWithAnimationView:_animation for:oneTime];
     }
}

//上报指纹录入数据
-(void)uploadUserData{
    //成员下添加指纹
    if (_isAddFinger) {
        [self addFingerData];
    }else{//添加成员和指纹
        [self uploadUserAndFingerData];
    }
}

-(void)addFingerData{
    [ZCTool showLoadingOnKeyWindow];
    NSDictionary *params = @{@"fingName":_fingerModel.fingName,
                             @"accessId":_accessId,
                             @"uid":kSTRING(_fingerModel.uid),
                             @"keyId":_fingerModel.keyId,
                             @"deviceId":kCurClickDevice.deviceId};
    [ZKHttpManager postWithPath:@"/msl_lock_key/LockFing/add" params:params finished:^(BOOL isSuccessed, id  _Nonnull result, NSString * _Nonnull code, NSString * _Nonnull message) {
        self->_isUploading = NO;
        [ZCTool hideLoadingOnKeyWindow];
        if (isSuccessed) {
            [self refreshWitUplaodSuccess];
        }
    }];
}

-(void)refreshWitUplaodSuccess{
    self->_sureBtn.hidden = NO;
    [self->_sureBtn setTitle:kLocalString(@"Done") forState:UIControlStateNormal];
    self->_tipLbl.text = kLocalString(@"Completed!");
    self->_tipLbl2.hidden = YES;
}

-(void)uploadUserAndFingerData{
    [ZCTool showLoadingOnKeyWindow];
    NSDictionary *fingerInfo = @{@"fingName":kLocalString(@"Fingerprint 1"),
                                 @"accessId":_accessId,
                                 @"uid":kSTRING(_keyModel.uid)};
    NSMutableArray *mslLockFingList = [[NSMutableArray alloc] init];
    [mslLockFingList addObject:fingerInfo];
    //上报成员和指纹数据
    NSDictionary *params = @{@"keyType":kSTRING(@(_keyModel.keyType)),
                             @"keyName":_keyModel.keyName,
                             @"uid":kSTRING(_keyModel.uid),
                             @"lockType":kSTRING(@(_keyModel.lockType)),
                             @"startTime":_keyModel.startTime,
                             @"endTime":_keyModel.endTime,
                             @"weekDays":[ZCTool objectToJson:_keyModel.weekDays],
                             @"dayStart":_keyModel.dayStart,
                             @"dayEnd":_keyModel.dayEnd,
                             @"deviceId":kCurClickDevice.deviceId,
                             @"mslLockFingList":mslLockFingList};
    [ZKHttpManager postWithPath:@"/msl_lock_key/add" params:params finished:^(BOOL isSuccessed, id  _Nonnull result, NSString * _Nonnull code, NSString * _Nonnull message) {
        [ZCTool hideLoadingOnKeyWindow];
        self->_isUploading = NO;
        if (isSuccessed) {
            NSDictionary *data = result[@"result"];
            self->_keyModel.keyId = data[@"keyId"];
            [self refreshWitUplaodSuccess];
        }
    }];
}

@end
